// SPDX-License-Identifier: MIT
// Copyright 2020 NXP

/**
 * @file custom.c
 *
 */

/*********************
 *      INCLUDES
 *********************/
#include <stdio.h>
#include "lvgl/lvgl.h"
#include "custom.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/

/**********************
 *  STATIC VARIABLES
 **********************/

/**
 * Create a demo application
 */
int     get_result(int old,int value,char opr)
{
    int res;
    switch (opr)
    {
    case 0:
        res = value;
        break;
    case 3://'+'
        res = old+value;
        break;
    case 7://'-':
        res = old-value;
        break;
    case 11://'*':
        res = old*value;
        break;
    case 15://'/':
        res = old/value;
        break;
    default:break;
    }
    return res;
}
static void calc_btnm_changed_event_cb(lv_event_t *e)
{
    lv_obj_t * obj = lv_event_get_target(e);
    lv_event_code_t code = lv_event_get_code(e);
    lv_ui * ui = lv_event_get_user_data(e);

    uint32_t id = lv_btnmatrix_get_selected_btn(obj);
    const char * txt = lv_btnmatrix_get_btn_text(obj, id);

    static char sbuf[9]={0};
    static char opr;
    static int old;
    int value;
    if(code == LV_EVENT_VALUE_CHANGED)
    {
        printf("id=%d,txt=%s\n",id,txt);
        switch (id)
        {
            case 3://'+'
            case 7://'-':
            case 11://'*':
            case 15://'/':

                sscanf(sbuf,"%d",&value);
                old = value;
                //old = get_result(old,)
                opr = id;
                memset(sbuf,0,sizeof(sbuf));
                break;
            case  14://'=':
                sscanf(sbuf,"%d",&value);
                old = get_result(old,value,opr);

                    lv_label_set_text_fmt(ui->screen_label_1,"%d",old);
                old = 0;
                opr = 0;
                memset(sbuf,0,sizeof(sbuf));
                break;
            case  12://clean:
                old = 0;
                opr = 0;
                memset(sbuf,0,sizeof(sbuf));
                    lv_label_set_text_fmt(ui->screen_label_1,"%d",old);
                break;
            default:    // 0-9
                if(strlen(sbuf)< sizeof(sbuf)-1){
                    strcat(sbuf,txt);
                    lv_label_set_text(ui->screen_label_1,sbuf);
                }
                break;
        }
    }
}
void custom_init(lv_ui *ui)
{
    /* Add your codes here */
    lv_obj_add_event_cb(ui->screen_btnm_1, calc_btnm_changed_event_cb, LV_EVENT_VALUE_CHANGED, ui);
}

